package com.example.autopia.view.Fragments

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.text.Editable
import android.text.TextWatcher
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.autopia.R
import com.example.autopia.databinding.FragmentParkingStatusBinding
import com.example.autopia.model.Item.News
import com.example.autopia.model.Item.Transaction
import com.example.autopia.model.Repositories.TestRepository
import com.example.autopia.model.Repositories.TransactionRepository
import com.example.autopia.model.Repositories.UsersRepository
import com.example.autopia.utilities.PreferenceManager
import com.example.autopia.view.Activities.AddBalanceActivity
import com.example.autopia.view.Activities.NewParkActivity
import com.example.autopia.view.Activities.ParkingActivity
import com.example.autopia.view.Activities.PaymentActivity
import com.example.autopia.view.Adapters.TransactionAdapter
import com.example.autopia.view.Listeners.TransactionListener
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase


class ParkingStatusFragment : Fragment() {

    private lateinit var binding: FragmentParkingStatusBinding
    private lateinit var adapter: TransactionAdapter
    private val repository = TransactionRepository()
    private val firebaseAuth = Firebase.auth
    private var transactions = ArrayList<Transaction>()
    private val userRepository = UsersRepository()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View? {
        binding = FragmentParkingStatusBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        adapter = TransactionAdapter()
        binding.recyclerView.adapter = adapter
        val sortedList = TestRepository.getTransactionList().sortedWith(compareByDescending { it.active })
        val check = userRepository.getUserById(firebaseAuth.currentUser?.uid ?: "")
        check.observe(viewLifecycleOwner) { curUser ->
            if (curUser.admin==1){
                adapter.setData(sortedList)
                repository.getAllItems().observe(viewLifecycleOwner){
                    transactions = it
                    binding.recyclerView.visibility = View.VISIBLE
                    binding.loading.visibility = View.GONE
                    adapter.setData(transactions.sortedWith(compareByDescending { it.active }))
                }
                binding.title.text = "Все транзакции"
                binding.etSearch.visibility = View.VISIBLE
                binding.btAdd.visibility = View.GONE
                binding.btPast.text = "Неактивные"

                binding.etSearch.addTextChangedListener(object : TextWatcher {
                    //Поиск по всем транзакциям
                    private val searchDelay = 600L
                    private val handler = Handler()
                    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
                    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

                    override fun afterTextChanged(s: Editable?) {
                        binding.loading.visibility = View.VISIBLE
                        binding.recyclerView.visibility = View.GONE
                        handler.removeCallbacksAndMessages(null) // Сбрасываем предыдущую задержку
                        handler.postDelayed({
                            performSearch()//Выполняем поиск
                        }, searchDelay)
                    }
                })

            }else{
                adapter.setData(sortedList)
                repository.getTransactionsByUserId(firebaseAuth.currentUser?.uid ?: "").observe(viewLifecycleOwner){
                    transactions = it
                    binding.recyclerView.visibility = View.VISIBLE
                    binding.loading.visibility = View.GONE
                    adapter.setData(transactions.sortedWith(compareByDescending { it.active }))
                }


            }
        }
        adapter.attachListener(object : TransactionListener {
            override fun onParkingStop() {
                startActivity(Intent(requireContext(), PaymentActivity::class.java))
            }

            override fun toParkingClick(transaction: Transaction) {
                val intent = Intent(requireContext(), ParkingActivity::class.java)
                intent.putExtra("parkingId", transaction.idPark)
                startActivity(intent)
            }

        })


        binding.apply {
            btAll.setOnClickListener {
                val sortedList = transactions.sortedWith(compareByDescending { it.active })
                adapter.setData(sortedList)
                btAll.setBackgroundResource(R.drawable.button_active_menu)
                btActive.setBackgroundResource(android.R.color.transparent)
                btPast.setBackgroundResource(android.R.color.transparent)
            }
            btActive.setOnClickListener {
                val trueList = transactions.filter { it.active }
                adapter.setData(trueList)
                btAll.setBackgroundResource(android.R.color.transparent)
                btActive.setBackgroundResource(R.drawable.button_active_menu)
                btPast.setBackgroundResource(android.R.color.transparent)
            }
            btPast.setOnClickListener {
                val falseList = transactions.filterNot { it.active }
                adapter.setData(falseList)
                btAll.setBackgroundResource(android.R.color.transparent)
                btActive.setBackgroundResource(android.R.color.transparent)
                btPast.setBackgroundResource(R.drawable.button_active_menu)
            }
            btAdd.setOnClickListener {
                val intent = Intent(requireContext(), AddBalanceActivity::class.java)
                startActivity(intent)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        userRepository.getUserById(firebaseAuth.currentUser?.uid ?: "").observe(viewLifecycleOwner){
            binding.tvBalance.text = it.balance.toString() + " ₽"
        }
    }
    fun performSearch() {
        var list = ArrayList<Transaction>()
        val items = repository.getAllItems()
        items.observe(viewLifecycleOwner) {
            list = it
            list = list.filter { trans ->
                trans.id.contains(
                    binding.etSearch.text.toString().trim()
                ) || trans.idPark.contains(binding.etSearch.text.toString().trim()) || trans.cardId.contains(binding.etSearch.text.toString().trim()) ||
                        trans.namePark.contains(binding.etSearch.text.toString().trim()) ||
                        trans.place!!.car!!.number.contains(binding.etSearch.text.toString().trim()) //Только удовлетворяющее поиску по названию и заголовку

            } as ArrayList<Transaction>
            adapter.setData(list)
            binding.loading.visibility = View.GONE
            binding.recyclerView.visibility = View.VISIBLE
        }
    }
}